package cn.edu.usst.cs.chat_room01;

import jakarta.servlet.annotation.WebListener;
import jakarta.servlet.http.HttpSessionEvent;
import jakarta.servlet.http.HttpSessionListener;

import java.time.LocalDateTime;

@WebListener
public class UserActivityListener implements HttpSessionListener {

    public UserActivityListener() {
    }


    @Override
    public void sessionCreated(HttpSessionEvent sessionEvent) {
        System.out.println("Session created");
        System.out.println(LocalDateTime.now());
        System.out.println(sessionEvent.getSession().getId());
        HttpSessionListener.super.sessionCreated(sessionEvent);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent sessionEvent) {
        Object user_raw = sessionEvent.getSession().getAttribute(ServletInterface.USER);
        if (user_raw == null) {
            System.out.println("unable to find user");
            return;
        }
        String user = user_raw.toString();
        HelloServlet servlet = HelloServlet.getInstance();
        if (servlet == null) {
            System.out.println("unable to find servlet");
            return;
        }
        servlet.logout(user);
        System.out.printf("sessionDestroyed for user %s at %s\n", user, LocalDateTime.now());
    }
}
